/*
 * Copyright (c) 2006-2021, Ulandlink Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2021-09-18     lfz         first version
 */
#include "drv_spi_flash.h"
#include "sfud_port.h"
#include "drv_gpio.h"
#include <drv_spi.h>
#include <fal.h>
#include <dfs_fs.h>
#include <easyflash.h>

#define FLASH_CS_PIN								 GET_PIN(A, 15)	// CS PA15
#define SPI_BUS_NAME								(SPI0_BUS_NAME)

#define FLASH_DEV_NAME								("w25q32")
#define FILES_SYSTEM_TYPE                           ("elm")

int32_t spi_flash_init(void)
{
    /* Attach the spi device to SPI bus */
	if (rt_hw_spi_device_attach(SPI_BUS_NAME, SPI_DEV_NAME, FLASH_CS_PIN) != RT_EOK){
		rt_kprintf("rt_hw_spi_device_attach() fail!\n");
		return -RT_ERROR;
	}
	
    /* Probe SPI flash by SFUD(Serial Flash Universal Driver) driver library and though SPI device */
	if (rt_sfud_flash_probe(FLASH_DEV_NAME, SPI_DEV_NAME) == RT_NULL){
		rt_kprintf("rt_sfud_flash_probe() fail!\n");
		return -RT_ERROR;
	}
	
    /* fal init*/
	if (fal_init() < 0){
		rt_kprintf("fal_init() fail!\n");
		return -RT_ERROR;
	}

    /* EasyFlash init*/
	if (easyflash_init() != EF_NO_ERR){	
		rt_kprintf("easyflash_init() fail!\n");
        return -RT_ERROR;
	}
    
#ifdef RT_USING_DFS_ELMFAT
	{
		extern int elm_init(void);
        
        /* Create a block device on the file system partition of spi flash */
        if (fal_blk_device_create(RT_DFS_ELM_NAME) == RT_NULL){
            rt_kprintf("fal_blk_device_create() fail!\n");
            return -RT_ERROR;
        }
    
		/* if enable elmfat, initialize and mount it as soon as possible */
		elm_init();

		/* mount the file system from "filesystem" partition of spi flash. */
		if (dfs_mount(RT_DFS_ELM_NAME, "/", FILES_SYSTEM_TYPE, 0, 0) != 0){
            dfs_mkfs(FILES_SYSTEM_TYPE, RT_DFS_ELM_NAME);
            rt_kprintf("dfs_mount() fail!\n");
            return -RT_ERROR;
        }
	}
#endif	/* RT_USING_DFS_ELMFAT */
	return RT_EOK;
}

INIT_DEVICE_EXPORT(spi_flash_init);
